package delivery.order.service.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

public class NumberFormatUtils {

    // 只能输入0123456789.并且不能点开头和结尾，最少包含一个数字
    private static final Pattern VALID_NUMBER_PATTERN = Pattern.compile("^(?=.*\\d)[1-9]\\d*(\\.\\d+)?$|^0(\\.\\d+)?$");

    /**
     * 格式化，保留2位小数（0.00）
     */
    public static HashMap<String, String> toTwoDecimals(String numberStr) {
        // 非空判断
        HashMap<String, String> respMap = new HashMap<>();
        if (numberStr == null || numberStr.trim().isEmpty()) {
            respMap.put("code", "001");
            respMap.put("str", "数字不能为空");
            return respMap;
        }
        // 数字判断
        if (!VALID_NUMBER_PATTERN.matcher(numberStr.trim()).matches()) {
            respMap.put("code", "002");
            respMap.put("str", "请输入合法的0~9数字");
            return respMap;
        }
        //格式化，保留2位小数（四舍五入）
        try {
            BigDecimal number = new BigDecimal(numberStr.trim());
            number = number.setScale(2, RoundingMode.HALF_UP); // 使用新的RoundingMode
            DecimalFormat df = new DecimalFormat("0.00");
            String format = df.format(number);
            respMap.put("code", "000");
            respMap.put("str", format);
            return respMap;
        } catch (Exception e) {
            throw new RuntimeException("输入格式无效", e);
        }
    }

    /**
     * 两个数相乘，保留2位小数
     */
    public static String multiplyDecimalFormat(String num1, String num2) {
        try {
            DecimalFormat df = new DecimalFormat("0.00");
            df.setRoundingMode(RoundingMode.HALF_UP);

            // 解析字符串为Number对象
            Number number1 = df.parse(num1);
            Number number2 = df.parse(num2);

            // 转换为BigDecimal以确保精度
            BigDecimal bd1 = new BigDecimal(number1.toString());
            BigDecimal bd2 = new BigDecimal(number2.toString());

            // 相乘并四舍五入到小数点后两位
            BigDecimal result = bd1.multiply(bd2).setScale(2, RoundingMode.HALF_UP);

            // 返回格式化后的字符串
            return df.format(result);
        } catch (Exception e) {
            throw new IllegalArgumentException("输入格式无效，请输入有效的数字格式", e);
        }
    }

    /**
     * 集合数相加（保留两位小数）
     */
    public static String calculateSum(List<String> allTotalList) {
        if (allTotalList == null || allTotalList.isEmpty()) {
            return "0.00";
        }

        BigDecimal total = BigDecimal.ZERO;

        for (String numberStr : allTotalList) {
            try {
                BigDecimal number = new BigDecimal(numberStr.trim());
                total = total.add(number);
            } catch (NumberFormatException e) {
                System.err.println("Invalid number format: " + numberStr);
            }
        }

        // 使用新的RoundingMode枚举，避免警告
        return total.setScale(2, RoundingMode.HALF_UP).toString();
    }

}
